#include "StdAfx.h"
#include "TinyBytes.h"

TinyBytes::TinyBytes(size_t len)
: _buf(new char[len]),
_bufLen(len),
_dataLen(0)
{
}

TinyBytes::~TinyBytes(void)
{
	delete []_buf;
}

TinyBytes::TinyBytes(const TinyBytes &other)
:_buf(NULL),
_bufLen(0),
_dataLen(0)
{
	operator = (other);
}

TinyBytes &TinyBytes::operator=(const TinyBytes &other)
{
	if (&other != this)
	{
		if (_buf != NULL)
		{
			delete []_buf;
		}

		_bufLen = other._bufLen;
		_buf = new char[_bufLen];
		_dataLen = other._dataLen;

		memcpy(_buf, other._buf, _bufLen);
	}

	return *this;
}

bool TinyBytes::push(const void *data, size_t len)
{
	if (len <= 0)
	{
		return false;
	}

	size_t space = _bufLen - _dataLen;

	if (space < len)
	{
		size_t nbuffLen = _dataLen + len;
		char *nbuff = new char[nbuffLen];
		memcpy(nbuff, _buf, _dataLen);

		delete []_buf;

		_buf = nbuff;
		_bufLen = nbuffLen;
	}

	memcpy(_buf + _dataLen, data, len);
	_dataLen += len;

	return true;
}

void TinyBytes::pop(size_t len)
{
	if (_dataLen < len)
	{
		_dataLen = 0;
	}
	else
	{
		memcpy(_buf, _buf + len, _dataLen - len);
		_dataLen -= len;
	}
}

void TinyBytes::clear()
{
	_dataLen = 0;
}

const void *TinyBytes::data()
{
	return _buf;
}

size_t TinyBytes::length()
{
	return _dataLen;
}
